package io.hankers.cordova;

import android.app.ActivityManager;
import android.speech.tts.TextToSpeech;
import android.util.Log;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import java.lang.reflect.Method;
import java.util.Locale;

import static android.content.Context.ACTIVITY_SERVICE;

public class XunfeiTTS extends CordovaPlugin implements TextToSpeech.OnInitListener {

    private static String TAG = XunfeiTTS.class.getSimpleName();

    private TextToSpeech _tts;

    @Override
    protected void pluginInitialize() {
        if (_tts == null) {
            _tts = new TextToSpeech(cordova.getContext(), this, "com.iflytek.speechcloud");
            _tts.setLanguage(Locale.CHINA);
            //_tts.setSpeechRate(0.8f);
        }
    }

    /**
     * Executes the request and returns PluginResult.
     *
     * @param action          The action to execute.
     * @param args            JSONArry of arguments for the plugin.
     * @param callbackContext The callback id used when calling back into JavaScript.
     * @return True if the action was valid, false if not.
     */
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        Log.d(TAG, action + "," + args);
        cordova.getThreadPool().execute(() -> {
            try {
                Method method = XunfeiTTS.class.getDeclaredMethod(action, JSONArray.class, CallbackContext.class);
                method.invoke(XunfeiTTS.this, args, callbackContext);
            } catch (Exception e) {
                Log.e(TAG, e.toString());
            }
        });
        return true;
    }

    void speakOut(JSONArray data, CallbackContext callbackContext) throws JSONException {
        final String msg = data.getString(0);

        _tts.speak(msg, TextToSpeech.QUEUE_ADD, null);

        Log.i(TAG, "Doing speakOut " + msg);
        logStatus();
    }

    @Override
    public void onInit(int status) {
        //setTvTips("面板status = " + status);
        //logfile("tts 完成初始化");
        Log.i(TAG, "tts 完成初始化");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (_tts != null) {
            _tts.stop();
            _tts.shutdown();
            _tts = null;
        }
    }

    private void logStatus() {
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        ActivityManager activityManager = (ActivityManager) cordova.getActivity().getSystemService(ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(mi);
        long availableMegs = mi.availMem / 1048576L;
        long totalMegs = mi.totalMem / 1048576L;
        Log.i(TAG, "availableMem=" + availableMegs + ", totalMem=" + totalMegs + ", lowMemory=" + mi.lowMemory);
    }
}
